define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox', 'model/group', 'stringUtils'], function ($, domReady, appLocalStorage, appConst, global, msgBox, groupM, stringUtils) {
    var components = {};
    var data = {
        searchFields: {},
        search_key: ""
    };

    var that;
    return {
        init: function () {
            that = this;
            components = {
                dt_groups: $('#dt_group_list'),
                btn_search: $('#btn_search'),
                txt_searchText: $('#txt_searchText')
            };

            data.search_key = appConst.searchKey.search_group_key + global.getUserId();


            that.initSearchBar();
            that.initGroupTable();
            // that.loadGroupTable();
        },
        initGroupTable: function () {
            components.dt_groups.dataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>>r" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing": true,
                "pageLength": global.getPageSize(),
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language,
                "ordering": false,
                "ajax": {
                    "url": 'group/list',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": function (params) {
                        return that.getSearchCondition(params);
                    },
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },

                "columns": [
                    {"data": null},
                    {"data": "id"},
                    {"data": "name"},
                    {"data": "description"},
                    {"data": null}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    // {
                    //     "targets": [3],
                    //     "render": function (d, type, full) {
                    //         return appConst.getFormatFieldText({
                    //             text: full.description
                    //         });
                    //     }
                    // },
                    {
                        "targets": [4],
                        "render": function (d, type, full) {
                            var id = full.id;
                            var aHref = '<a href="javascript:void(0);" class="deleteGroupConfirm" data-gcode="' + id + '" data-gname="' + full.name + '">' + $.i18n.prop("GLOBAL_DELETE") + '</a> '

                            var operate = '<div class="center">'
                                + '<a href="#group/edit/' + id + '" class="details-control">' + $.i18n.prop("GLOBAL_OPERATE_DETAIL") + '</a>' + ' '
                                + aHref + '</div>';
                            return operate;
                        }
                    }
                ]
            });

            global.drawNumber_bg(components.dt_groups, function () {
                components.dt_groups.find(".deleteGroupConfirm").unbind('click').on('click', function (obj) {
                    that.showDeleteGroupConfirm({id: $(this).attr("data-gcode"), name: $(this).attr("data-gname")});
                });
            });
        },
        initSearchBar: function () {
            components.btn_search.click(function (e) {
                data.searchFields.search_LIKE_name = components.txt_searchText.val();
                appLocalStorage.setLocal(data.search_key, JSON.stringify(data.searchFields));
                that.loadGroupTable();
            });
        },
        loadGroupTable: function () {
            components.dt_groups.dataTable().api().ajax.url('group/list').load();
        },
        showDeleteGroupConfirm: function (group) {
            var id = group.id;
            var name = group.name;
            msgBox.show({
                title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                content: "" + $.i18n.prop("GROUP_DELETE_CONFIRM_CONTENT", [name]) + " <p class='text-align-right'>" +
                "<button type='submit' id='" + id + "' data-gcode='" + id + "' class='btn btn-primary btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal',
                timeout: false,
                clean: true
            });
            $('#divSmallBoxes').find('button[data-gcode=' + id + ']').unbind('click').on('click', function (e) {
                e.preventDefault();
                that.deleteGroup(group);
            });
        },
        deleteGroup: function (group) {
            groupM.deleteGroup(group.id, function (d) {
                msgBox.successBox({
                    content: $.i18n.prop('GLOBAL_DELETE_SUCCESS', group.name)
                });

                that.loadGroupTable();
            }, function (msg) {
                console.log(msg);
            })
        },
        getSearchCondition: function (params) {
            data.searchFields = {
                search_LIKE_name: components.txt_searchText.val()
            };

            var queryCondition;
            var localParam = appLocalStorage.getLocal(data.search_key);
            if (stringUtils.isNotBlank(localParam)) {
                queryCondition = JSON.parse(localParam);

                if (stringUtils.isNotBlank(queryCondition.search_LIKE_name)) {
                    components.txt_searchText.val(queryCondition.search_LIKE_name);
                }
                data.searchFields = queryCondition;
            }

            $.extend(params, data.searchFields);
            params['draw'] = params.draw;

            return params;
        }
    };
});
